package com.sunrise.gateway.commons;

import com.google.common.base.Charsets;
import org.springframework.util.Base64Utils;

import java.io.IOException;

/**
 * Created by wangmin on 2017/7/4.
 */
public abstract class SafeUrlBase64Utils {
    public static String safeUrlBase64Encode(byte[] data) {
        String encodeBase64 = new String(Base64Utils.encode(data), Charsets.UTF_8);
        String safeBase64Str = encodeBase64.replace('+', '-');
        safeBase64Str = safeBase64Str.replace('/', '_');
        safeBase64Str = safeBase64Str.replaceAll("=", "");
        return safeBase64Str;
    }

    public static byte[] safeUrlBase64Decode(final String safeBase64Str) throws IOException {
        String base64Str = safeBase64Str.replace('-', '+');
        base64Str = base64Str.replace('_', '/');
        int mod4 = base64Str.length() % 4;
        if (mod4 > 0) {
            base64Str = base64Str + "====".substring(mod4);
        }

        return Base64Utils.decode(base64Str.getBytes());
    }


    public static void main(String[] s) throws Exception {
        //String res = safeUrlBase64Encode("王敏 杭州 [dateTime,format=yyyy-MM-dd]".getBytes());
        //System.out.println("res = " + res);
        //byte[] bytes = safeUrlBase64Decode("W2RhdGVUaW1lLGZvcm1hdD15eXl5LU1NLWRkXQ");
        //System.out.println("result = " + new String(bytes, "UTF-8"));
    }
}
